package com.originskyseed.platform.count.controller;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.originskyseed.platform.common.api.config.LoginConfig;
import com.originskyseed.platform.common.api.constant.RedisKeyConstans;
import com.originskyseed.platform.core.config.bean.ConfigManager;
import com.originskyseed.platform.core.redis.util.RedisUtil;
import com.originskyseed.platform.count.model.FinancialManage;
import org.apache.dubbo.config.annotation.DubboReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.originskyseed.platform.core.base.BaseController;
import com.originskyseed.platform.core.base.BaseLocaleResource;
import com.originskyseed.platform.core.base.BasePage;
import com.originskyseed.platform.core.base.BaseResponseBody;
import com.originskyseed.platform.core.common.code.CommonResponseCode;
import com.originskyseed.platform.core.filter.helper.SingleSignOnTokenHelper;
import com.originskyseed.platform.count.i18n.CountResponseMsg;
import com.originskyseed.platform.count.service.IFinancialManageService;
import com.originskyseed.platform.count.service.IUserSalaryService;
import com.originskyseed.platform.count.vo.request.HomePageCountVO;
import com.originskyseed.platform.log.model.HomePageCache;
import com.originskyseed.platform.log.service.IHomePageCacheService;
import com.originskyseed.platform.user.model.Dept;
import com.originskyseed.platform.user.model.UserInfo;
import com.originskyseed.platform.user.service.IDeptService;
import com.originskyseed.platform.user.service.IPlayerService;
import com.originskyseed.platform.user.service.IUserInfoService;

/**
 * 推广类统计 事业厅、小组 Controller类
 * 
 * @author Tangwanghui
 */
@Controller
@RequestMapping("/homePageGroupCount")
@BaseLocaleResource(localeFileName = "i18n_count")
public class HomePageGroupCountController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(HomePageGroupCountController.class);

	@DubboReference
	private IUserSalaryService userSalaryService;

	@DubboReference
	private IDeptService deptService;

	@DubboReference
	private IUserInfoService userInfoService;

	@DubboReference
	private IPlayerService playerService;

	@DubboReference
	private IFinancialManageService financialManageService;

	@DubboReference
	private IHomePageCacheService homePageCacheService;

	/**
	 * 查询所属公会
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/selectGroupHomePage.json")
	public BaseResponseBody selectGroupHomePage(HttpServletRequest request) {
		BaseResponseBody result = null;
		try {
			// 要返回的对象
			String name = "";

			// 当前用户信息
			UserInfo userInfo = SingleSignOnTokenHelper.getCurrentUserInfo(UserInfo.class);

			// 部门id
			String deptId = this.getParameterString("deptId", null);
			if (deptId == null) {
				deptId = userInfo.getDeptId();
			}
			Dept dept = this.deptService.selectByPrimaryKey(deptId);
			if (dept != null) {
				name = selectLabourUnionId(dept.getCode());
			}
			result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), CountResponseMsg.DATA_SELECT_SUCCESS.getMsg()), name);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), CountResponseMsg.DATA_SELECT_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 查询任务汇总
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/selectTaskSummary.json")
	public BaseResponseBody selectTaskSummary(HttpServletRequest request) {
		BaseResponseBody result = null;
		try {
			// 要返回的对象
			Map<String, Object> map = new HashMap<>();

			// 当前用户信息
			UserInfo userInfo = SingleSignOnTokenHelper.getCurrentUserInfo(UserInfo.class);
            if(userInfo==null)
			{
				result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), CountResponseMsg.DATA_SELECT_ERROR.getMsg()), null, null);
                return result;
			}
			// 类型 0 我发布的 1 公会内的
			Integer type = this.getParameterInteger("type", null);
			// 部门id
			String deptId = this.getParameterString("deptId", null);
			if (deptId == null) {
				deptId = userInfo.getDeptId();
			}
			Dept dept = this.deptService.selectByPrimaryKey(deptId);
			if (dept != null) {
				List<String> list = new ArrayList<>();
				list.add(dept.getId());
				selectSonId(dept.getCode(), list);
				List<String> userList = new ArrayList<>();
				if (type == 0) {
					userList.add(userInfo.getId());
				} else {
					userList = this.userInfoService.selectSalesmanIdsByDeptIds(list);
				}
				map = this.playerService.selectTaskSummary(userList);
			}

			result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), CountResponseMsg.DATA_SELECT_SUCCESS.getMsg()), map);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), CountResponseMsg.DATA_SELECT_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 查询业务员逾期情况
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/selectSalesmanOverdue.json")
	public BaseResponseBody selectSalesmanOverdue(HttpServletRequest request) {
		BaseResponseBody result = null;
		try {
			// 要返回的对象
			Map<String, Object> resultMap = new HashMap<>();
			// 行和列
			List<String> columnList = new ArrayList<>();
			List<BigDecimal> rowList = new ArrayList<>();
			List<BigDecimal> row1List = new ArrayList<>();

			// 当前用户信息
			UserInfo userInfo = SingleSignOnTokenHelper.getCurrentUserInfo(UserInfo.class);

			// 类型 0 日 1 周 2 月
			Integer type = this.getParameterInteger("type", null);
			// 部门id
			String deptId = this.getParameterString("deptId", null);
			if (deptId == null) {
				deptId = userInfo.getDeptId();
			}
			Dept dept = this.deptService.selectByPrimaryKey(deptId);
			if (dept != null) {
				List<String> list = new ArrayList<>();
				list.add(dept.getId());
				selectSonId(dept.getCode(), list);
				List<String> userList = this.userInfoService.selectUserIdsByDeptIds(list);
				List<Map<String, Object>> mapList = new ArrayList<>();
				if (userList.size() > 0) {
					mapList = this.playerService.selectSalesmanOverdue(type, userList);
				}

				for (Map<String, Object> map1 : mapList) {
					columnList.add((String) map1.get("name"));
					rowList.add((BigDecimal) map1.get("expect"));
					row1List.add((BigDecimal) map1.get("completed"));
				}
			}
			resultMap.put("columnList", columnList);
			resultMap.put("expectList", rowList);
			resultMap.put("completedList", row1List);

			result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), CountResponseMsg.DATA_SELECT_SUCCESS.getMsg()), resultMap);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), CountResponseMsg.DATA_SELECT_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 查询KPI
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/selectKPI.json")
	public BaseResponseBody selectKPI(HttpServletRequest request) {
		BaseResponseBody result = null;
		try {
			// 部门id
			String deptId = this.getParameterString("deptId", null);
			// 类型 0日，1周，2月，3季，4年
			Integer type = this.getParameterInteger("type", null);

			// 要返回的数据
			Map<String, Object> map = null;

			// 从redis中查询是否存在
			if(type==0){
				map = (Map<String, Object>)RedisUtil.getInstance().getForObject(RedisKeyConstans.HOME_PAGE_KEY+deptId+"selectKPIDAY");
			} else if (type==1){
				map =  (Map<String, Object>)RedisUtil.getInstance().getForObject(RedisKeyConstans.HOME_PAGE_KEY+deptId+"selectKPIWEEK");
			} else if(type == 2 ){
				map =  (Map<String, Object>)RedisUtil.getInstance().getForObject(RedisKeyConstans.HOME_PAGE_KEY+deptId+"selectKPIMONTH");
			}else if(type == 3 ) {
				map =  (Map<String, Object>)RedisUtil.getInstance().getForObject(RedisKeyConstans.HOME_PAGE_KEY+deptId+"selectKPIQUARTER");
			}else{
				map =  (Map<String, Object>)RedisUtil.getInstance().getForObject(RedisKeyConstans.HOME_PAGE_KEY+deptId+"selectKPIYEAR");
			}

			// 如果redis里面为空，则查询数据库，并且存进redis里面
			if(map==null){
				map = new HashMap<>();
				List<String> columnList = new ArrayList<>();
				List<BigDecimal> rowList = new ArrayList<>();
				List<BigDecimal> row1List = new ArrayList<>();
				// 获取小组下所有业务员
				UserInfo queryUser = new UserInfo();
				queryUser.setType(6);
				queryUser.setDeptId(deptId);
				List<UserInfo> userInfoList = this.userInfoService.selectList(queryUser);
				for (UserInfo userInfo : userInfoList) {
					// 业务员id
					List<String> userList = new ArrayList<>();
					userList.add(userInfo.getOtherAccount());

					// 查询主播营收值
					BigDecimal revenueValue;
					if (userList.size() > 0) {
						revenueValue = this.playerService.selectRevenueValue(type, userList, 0);
					} else {
						revenueValue = BigDecimal.ZERO;
					}

					BigDecimal kpi = BigDecimal.ZERO;
					FinancialManage query = new FinancialManage();
					query.setObjId(userInfo.getId());
					query.setType(2);
					query.setStartTime(getMonthFirstDay());
					List<FinancialManage> financialManageList = this.financialManageService.selectList(query);
					for (FinancialManage financialManage : financialManageList) {
						kpi = kpi.add(financialManage.getAmount());
					}

					if (type == 0) {
						kpi = kpi.divide(new BigDecimal(30), 2, BigDecimal.ROUND_HALF_UP);
					} else if (type == 1) {
						kpi = kpi.divide(new BigDecimal(4), 2, BigDecimal.ROUND_HALF_UP);
					} else if (type == 3) {
						kpi = kpi.multiply(new BigDecimal(4));
					} else if (type == 4) {
						kpi = kpi.multiply(new BigDecimal(12));
					}
					rowList.add(revenueValue);
					row1List.add(kpi);
					columnList.add(userInfo.getName());
				}
				map.put("columnList", columnList);
				map.put("kipCompleteList", rowList);
				map.put("kipTargetList", row1List);

				// 存进redis中
				if(type==0){
					RedisUtil.getInstance().setForObject(RedisKeyConstans.HOME_PAGE_KEY+deptId+"selectKPIDAY",map,getCacheInvalidTime());
				} else if (type==1){
					RedisUtil.getInstance().setForObject(RedisKeyConstans.HOME_PAGE_KEY+deptId+"selectKPIWEEK",map,getCacheInvalidTime());
				} else if(type == 2 ){
					RedisUtil.getInstance().setForObject(RedisKeyConstans.HOME_PAGE_KEY+deptId+"selectKPIMONTH",map,getCacheInvalidTime());
				}else if(type == 3 ) {
					RedisUtil.getInstance().setForObject(RedisKeyConstans.HOME_PAGE_KEY+deptId+"selectKPIQUARTER",map,getCacheInvalidTime());
				}else{
					RedisUtil.getInstance().setForObject(RedisKeyConstans.HOME_PAGE_KEY+deptId+"selectKPIYEAR",map,getCacheInvalidTime());
				}
			}
			result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), CountResponseMsg.DATA_SELECT_SUCCESS.getMsg()), map);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), CountResponseMsg.DATA_SELECT_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 查询业绩总览
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/selectPerformanceOverview.json")
	public BaseResponseBody selectPerformanceOverview(HttpServletRequest request) {
		BaseResponseBody result = null;
		try {
			// 部门id
			String deptId = this.getParameterString("deptId", null);

			// 从redis中查询是否存在
			Map<String, Object> map = (Map<String, Object>) RedisUtil.getInstance().getForObject(RedisKeyConstans.HOME_PAGE_KEY+deptId+"selectPerformanceOverview");

			//redis里面没有则直接查询，并且存进redis里面
			if(map == null){
				map = new HashMap<>();
				Dept dept = this.deptService.selectByPrimaryKey(deptId);
				if (dept != null) {
					List<String> list = new ArrayList<>();
					list.add(dept.getId());
					selectSonId(dept.getCode(), list);
					List<String> userList = this.userInfoService.selectSalesmanIdsByDeptIds(list);
					if (userList != null && userList.size() > 0) {
						// 今日充值总金额
						BigDecimal todayAmount = this.playerService.selectRechargeUserAmountByDate(0, userList);
						if (todayAmount == null) {
							todayAmount = new BigDecimal(BigInteger.ZERO);
						}
						map.put("todayRevenue", todayAmount.multiply(new BigDecimal(0.3)));
						map.put("todayAmount", todayAmount);

						// 本月充值总金额
						BigDecimal monthAmount = this.playerService.selectRechargeUserAmountByDate(2, userList);
						if (monthAmount == null) {
							monthAmount = new BigDecimal(BigInteger.ZERO);
						}
						map.put("monthRevenue", monthAmount.multiply(new BigDecimal(0.3)));
						map.put("monthAmount", monthAmount);

						// 总充值金额
						BigDecimal amount = this.playerService.selectRechargeUserAmountByDate(-1, userList);
						map.put("amount", amount);
					} else {
						map.put("todayRevenue", 0);
						map.put("todayAmount", 0);
						map.put("monthRevenue", 0);
						map.put("monthAmount", 0);
						map.put("amount", 0);
					}

					// 存进redis里面
					RedisUtil.getInstance().setForObject(RedisKeyConstans.HOME_PAGE_KEY+deptId+"selectPerformanceOverview",map,getCacheInvalidTime());
				}
			}
			result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), CountResponseMsg.DATA_SELECT_SUCCESS.getMsg()), map);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), CountResponseMsg.DATA_SELECT_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 查询工会营收统计图
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/selectGuildRevenueStatistics.json")
	public BaseResponseBody selectGuildRevenueStatistics(HttpServletRequest request) {
		BaseResponseBody result = null;
		try {
			// 类型 0日，1周，2月，3季，4年
			Integer type = this.getParameterInteger("type", null);
			// 部门id
			String deptId = this.getParameterString("deptId", null);
			// 要返回的数据
			Map<String, Object> map = null;

			// 从redis中查询是否存在
			if(type==0){
				map = (Map<String, Object>)RedisUtil.getInstance().getForObject(RedisKeyConstans.HOME_PAGE_KEY+deptId+"selectGuildRevenueStatisticsDAY");
			} else if (type==1){
				map =  (Map<String, Object>)RedisUtil.getInstance().getForObject(RedisKeyConstans.HOME_PAGE_KEY+deptId+"selectGuildRevenueStatisticsWEEK");
			} else{
				map =  (Map<String, Object>)RedisUtil.getInstance().getForObject(RedisKeyConstans.HOME_PAGE_KEY+deptId+"selectGuildRevenueStatisticsMONTH");
			}

			// 如果redis里面为空，则查询数据库，并且存进redis里面
			if(map==null){
				map = new HashMap<>();
				Dept dept = this.deptService.selectByPrimaryKey(deptId);
				if (dept != null) {
					List<String> list = new ArrayList<>();
					list.add(dept.getId());
					selectSonId(dept.getCode(), list);
					List<String> userList = this.userInfoService.selectSalesmanIdsByDeptIds(list);
					if (userList.size() > 0) {
						map = this.playerService.selectUserRechargeStatistics(type, userList, 0);

						// 存进redis里面
						if(type==0){
							RedisUtil.getInstance().setForObject(RedisKeyConstans.HOME_PAGE_KEY+deptId+"selectGuildRevenueStatisticsDAY",map,getCacheInvalidTime());
						} else if (type==1){
							RedisUtil.getInstance().setForObject(RedisKeyConstans.HOME_PAGE_KEY+deptId+"selectGuildRevenueStatisticsWEEK",map,getCacheInvalidTime());
						} else{
							RedisUtil.getInstance().setForObject(RedisKeyConstans.HOME_PAGE_KEY+deptId+"selectGuildRevenueStatisticsMONTH",map,getCacheInvalidTime());
						}
					}
				}
			}
			result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), CountResponseMsg.DATA_SELECT_SUCCESS.getMsg()), map);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), CountResponseMsg.DATA_SELECT_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 查询用户充值金额统计图
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/selectUserRechargeStatistics.json")
	public BaseResponseBody selectUserRechargeStatistics(HttpServletRequest request) {
		BaseResponseBody result = null;
		try {
			// 类型 0日，1周，2月，3季，4年
			Integer type = this.getParameterInteger("type", null);
			// 部门id
			String deptId = this.getParameterString("deptId", null);
			// 要返回的数据
			Map<String, Object> map = null;

			// 从redis中查询是否存在
			if(type==0){
				map = (Map<String, Object>)RedisUtil.getInstance().getForObject(RedisKeyConstans.HOME_PAGE_KEY+deptId+"selectUserRechargeStatisticsDAY");
			} else if (type==1){
				map =  (Map<String, Object>)RedisUtil.getInstance().getForObject(RedisKeyConstans.HOME_PAGE_KEY+deptId+"selectUserRechargeStatisticsWEEK");
			} else{
				map =  (Map<String, Object>)RedisUtil.getInstance().getForObject(RedisKeyConstans.HOME_PAGE_KEY+deptId+"selectUserRechargeStatisticsMONTH");
			}


			// 如果redis里面为空，则查询数据库，并且存进redis里面
			if(map==null){
				map = new HashMap<>();
				Dept dept = this.deptService.selectByPrimaryKey(deptId);
				if (dept != null) {
					List<String> list = new ArrayList<>();
					list.add(dept.getId());
					selectSonId(dept.getCode(), list);
					List<String> userList = this.userInfoService.selectSalesmanIdsByDeptIds(list);
					if (userList.size() > 0) {
						map = this.playerService.selectUserRechargeStatistics(type, userList, 1);

						// 存进redis里面
						if(type==0){
							RedisUtil.getInstance().setForObject(RedisKeyConstans.HOME_PAGE_KEY+deptId+"selectUserRechargeStatisticsDAY",map,getCacheInvalidTime());
						} else if (type==1){
							RedisUtil.getInstance().setForObject(RedisKeyConstans.HOME_PAGE_KEY+deptId+"selectUserRechargeStatisticsWEEK",map,getCacheInvalidTime());
						} else{
							RedisUtil.getInstance().setForObject(RedisKeyConstans.HOME_PAGE_KEY+deptId+"selectUserRechargeStatisticsMONTH",map,getCacheInvalidTime());
						}
					}
				}
			}
			result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), CountResponseMsg.DATA_SELECT_SUCCESS.getMsg()), map);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), CountResponseMsg.DATA_SELECT_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 分页查询潜力用户
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/selectPotentialUsersByPage.json")
	public BaseResponseBody selectPotentialUsersByPage(HttpServletRequest request) {
		BaseResponseBody result = null;
		try {
			// 请求对象
			HomePageCountVO requestVO = this.getParameterBean(HomePageCountVO.class);

			// 当前用户信息
			UserInfo userInfo = SingleSignOnTokenHelper.getCurrentUserInfo(UserInfo.class);

			// 部门id
			String deptId = this.getParameterString("deptId", null);
			if (deptId == null) {
				deptId = userInfo.getDeptId();
			}
			Dept dept = this.deptService.selectByPrimaryKey(deptId);
			// 分页查询
			BasePage<Map<String, Object>> page = new BasePage<Map<String, Object>>(requestVO.getPageNo(), requestVO.getPageSize());
			if (dept != null) {
				List<String> list = new ArrayList<>();
				list.add(dept.getId());
				selectSonId(dept.getCode(), list);
				List<String> userList = this.userInfoService.selectSalesmanIdsByDeptIds(list);
				requestVO.setList(userList);
				if (userList.size() > 0) {
					page = this.playerService.selectPotentialUsersByPage(requestVO.toMap(), page);
				}
			}
			result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), CountResponseMsg.DATA_SELECT_SUCCESS.getMsg()), page);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), CountResponseMsg.DATA_SELECT_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 分页查询优质用户
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/selectHighQualityUsersByPage.json")
	public BaseResponseBody selectHighQualityUsersByPage(HttpServletRequest request) {
		BaseResponseBody result = null;
		try {
			// 请求对象
			HomePageCountVO requestVO = this.getParameterBean(HomePageCountVO.class);
			// 当前用户信息
			UserInfo userInfo = SingleSignOnTokenHelper.getCurrentUserInfo(UserInfo.class);

			// 部门id
			String deptId = this.getParameterString("deptId", null);
			if (deptId == null) {
				deptId = userInfo.getDeptId();
			}
			Dept dept = this.deptService.selectByPrimaryKey(deptId);
			// 分页查询
			BasePage<Map<String, Object>> page = new BasePage<Map<String, Object>>(requestVO.getPageNo(), requestVO.getPageSize());
			if (dept != null) {
				List<String> list = new ArrayList<>();
				list.add(dept.getId());
				selectSonId(dept.getCode(), list);
				List<String> userList = this.userInfoService.selectSalesmanIdsByDeptIds(list);
				requestVO.setList(userList);
				if (userList.size() > 0) {
					page = this.playerService.selectHighQualityUsersByPage(requestVO.toMap(), page);
				}
			}
			for (Map<String, Object> map : page.getResults()) {
				String belongBusinessId = (String) map.get("belongBusinessId");
				UserInfo userInfo1 = this.userInfoService.selectByOtherAccount(belongBusinessId);
				if(userInfo1!=null){
					map.put("belongBusinessAccount", userInfo1.getAccount());
					map.put("belongBusinessId", userInfo1.getId());
					map.put("belongBusinessName", userInfo1.getName());
				}
			}
			result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), CountResponseMsg.DATA_SELECT_SUCCESS.getMsg()), page);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), CountResponseMsg.DATA_SELECT_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 分页查询私域流量池用户
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/selectFlowPoolUsersByPage.json")
	public BaseResponseBody selectFlowPoolUsersByPage(HttpServletRequest request) {
		BaseResponseBody result = null;
		try {
			// 请求对象
			HomePageCountVO requestVO = this.getParameterBean(HomePageCountVO.class);
			// 当前用户信息
			UserInfo userInfo = SingleSignOnTokenHelper.getCurrentUserInfo(UserInfo.class);

			// 部门id
			String deptId = this.getParameterString("deptId", null);
			if (deptId == null) {
				deptId = userInfo.getDeptId();
			}
			Dept dept = this.deptService.selectByPrimaryKey(deptId);
			// 分页查询
			BasePage<Map<String, Object>> page = new BasePage<Map<String, Object>>(requestVO.getPageNo(), requestVO.getPageSize());
			if (dept != null) {
				List<String> list = new ArrayList<>();
				list.add(dept.getId());
				selectSonId(dept.getCode(), list);
				List<String> userList = this.userInfoService.selectSalesmanIdsByDeptIds(list);
				if (userList.size() > 0) {
					requestVO.setList(userList);
					page = this.playerService.selectFlowPoolUsersByPage(requestVO.toMap(), page);
				}

			}

			result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), CountResponseMsg.DATA_SELECT_SUCCESS.getMsg()), page);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), CountResponseMsg.DATA_SELECT_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 查询工会用户
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/selectUnionUsers.json")
	public BaseResponseBody selectUnionUsers(HttpServletRequest request) {
		BaseResponseBody result = null;
		try {
			// 部门id
			String deptId = this.getParameterString("deptId", null);

			// 从redis中查询是否存在
			Map<String, Object> map = (Map<String, Object>)RedisUtil.getInstance().getForObject(RedisKeyConstans.HOME_PAGE_KEY+deptId+"selectUnionUsers");
			// 如果查询不到就查询数据库，并且放进redis中
			if(map==null){
				map = new HashMap<>();
				Dept dept = this.deptService.selectByPrimaryKey(deptId);
				if (dept != null) {
					List<String> list = new ArrayList<>();
					list.add(dept.getId());
					selectSonId(dept.getCode(), list);
					List<String> userList = this.userInfoService.selectSalesmanIdsByDeptIds(list);
					if (userList.size() > 0) {
						map = this.playerService.selectUnionUsers(userList);
					}
				}

				// 存到redis中
				RedisUtil.getInstance().setForObject(RedisKeyConstans.HOME_PAGE_KEY+deptId+"selectUnionUsers",map,getCacheInvalidTime());
			}
			result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), CountResponseMsg.DATA_SELECT_SUCCESS.getMsg()), map);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), CountResponseMsg.DATA_SELECT_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 查询业务员排行榜
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/selectSalesmanRanking.json")
	public BaseResponseBody selectSalesmanRanking(HttpServletRequest request) {
		BaseResponseBody result = null;
		try {
			// 要返回的对象
			List<Map<String, Object>> resultList = new ArrayList<>();

			// 当前用户信息
			UserInfo userInfo = SingleSignOnTokenHelper.getCurrentUserInfo(UserInfo.class);
			// 类型 0查询工会内 1查询全部
			Integer type = this.getParameterInteger("type", null);
			// 部门id
			String deptId = this.getParameterString("deptId", null);
			if (deptId == null) {
				deptId = userInfo.getDeptId();
			}
			Dept dept = this.deptService.selectByPrimaryKey(deptId);
			if (dept != null) {
				List<String> list = new ArrayList<>();
				list.add(dept.getId());
				selectSonId(dept.getCode(), list);
				List<String> userList = this.userInfoService.selectSalesmanIdsByDeptIds(list);
				Map<String, Object> query = new HashMap<>();
				if (type == 0) {
					query.put("list", userList);
				}
				resultList = this.playerService.selectSalesmanRanking(query);
				for (Map<String, Object> map : resultList) {
					String depId = (String) map.get("deptId");
					String deptName = selectLabourUnionNameById(depId);
					map.put("deptName", deptName);
				}
			}

			result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), CountResponseMsg.DATA_SELECT_SUCCESS.getMsg()), resultList);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), CountResponseMsg.DATA_SELECT_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 查询新增注册用户统计
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/selectNewRegisteredUsers.json")
	public BaseResponseBody selectNewRegisteredUsers(HttpServletRequest request) {
		BaseResponseBody result = null;
		try {
			// 类型 0日，1周，2月，3季，4年
			Integer type = this.getParameterInteger("type", null);
			// 部门id
			String deptId = this.getParameterString("deptId", null);

			// 要返回的数据
			Map<String, Object> map = null;
			// 从redis中查询是否存在
			if(type==0){
				map = (Map<String, Object>)RedisUtil.getInstance().getForObject(RedisKeyConstans.HOME_PAGE_KEY+deptId+"selectNewRegisteredUsersDAY");
			} else if (type==1){
				map =  (Map<String, Object>)RedisUtil.getInstance().getForObject(RedisKeyConstans.HOME_PAGE_KEY+deptId+"selectNewRegisteredUsersWEEK");
			} else{
				map =  (Map<String, Object>)RedisUtil.getInstance().getForObject(RedisKeyConstans.HOME_PAGE_KEY+deptId+"selectNewRegisteredUsersMONTH");
			}

			// 如果redis里面为空，则查询数据库，并且存进redis里面
			if(map==null){
				map = new HashMap<>();
				Dept dept = this.deptService.selectByPrimaryKey(deptId);
				if (dept != null) {
					List<String> list = new ArrayList<>();
					list.add(dept.getId());
					selectSonId(dept.getCode(), list);
					List<String> userList = this.userInfoService.selectSalesmanIdsByDeptIds(list);
					if (userList.size() > 0) {
						map = this.playerService.selectNewRegisteredUsers(userList, type);

						// 存进redis里面
						if(type==0){
							RedisUtil.getInstance().setForObject(RedisKeyConstans.HOME_PAGE_KEY+deptId+"selectSalesmanRankingDAY",map,getCacheInvalidTime());
						} else if (type==1){
							RedisUtil.getInstance().setForObject(RedisKeyConstans.HOME_PAGE_KEY+deptId+"selectSalesmanRankingWEEK",map,getCacheInvalidTime());
						} else{
							RedisUtil.getInstance().setForObject(RedisKeyConstans.HOME_PAGE_KEY+deptId+"selectSalesmanRankingMONTH",map,getCacheInvalidTime());
						}
					}
				}
			}
			result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), CountResponseMsg.DATA_SELECT_SUCCESS.getMsg()), map);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), CountResponseMsg.DATA_SELECT_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}


	/**
	 * 查询优质用户
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/selectHighQualityUsers.json")
	public BaseResponseBody selectHighQualityUsers(HttpServletRequest request) {
		BaseResponseBody result = null;
		try {
			// 获取参数
			String deptId = this.getParameterString("deptId", null);
			// 类型 0日，1周，2月
			Integer type = this.getParameterInteger("type", null);

			// 要返回的数据
			Map<String, Object> map = null;
			// 从redis中查询是否存在
			if(type==0){
				map = (Map<String, Object>)RedisUtil.getInstance().getForObject(RedisKeyConstans.HOME_PAGE_KEY+deptId+"selectHighQualityUsersDAY");
			} else if (type==1){
				map =  (Map<String, Object>)RedisUtil.getInstance().getForObject(RedisKeyConstans.HOME_PAGE_KEY+deptId+"selectHighQualityUsersWEEK");
			} else{
				map =  (Map<String, Object>)RedisUtil.getInstance().getForObject(RedisKeyConstans.HOME_PAGE_KEY+deptId+"selectHighQualityUsersMONTH");
			}

			// 如果redis里面为空，则查询数据库，并且存进redis里面
			if(map==null){
				map = new HashMap<>();
				UserInfo userInfo = this.userInfoService.selectByPrimaryKey(deptId);
				// 业务员查询
				if (userInfo != null) {
					List<String> userList = new ArrayList<>();
					userList.add(userInfo.getOtherAccount());
					map = this.playerService.selectHighQualityUsers(type,userList, 0);
				} else {
					// 获取下级
					Dept queryDept = this.deptService.selectByPrimaryKey(deptId);
					List<String> userList = new ArrayList<>();
					if (queryDept != null) {
						List<String> deptIds = new ArrayList<>();
						deptIds.add(deptId);
						this.selectSonId(queryDept.getCode(), deptIds);
						userList = this.userInfoService.selectSalesmanIdsByDeptIds(deptIds);
					}
					if (userList.size() > 0) {
						map = this.playerService.selectHighQualityUsers(type,userList, 0);
					}
				}

				// 存进redis里面
				if(type==0){
					RedisUtil.getInstance().setForObject(RedisKeyConstans.HOME_PAGE_KEY+deptId+"selectHighQualityUsersDAY",map,getCacheInvalidTime());
				} else if (type==1){
					RedisUtil.getInstance().setForObject(RedisKeyConstans.HOME_PAGE_KEY+deptId+"selectHighQualityUsersWEEK",map,getCacheInvalidTime());
				} else{
					RedisUtil.getInstance().setForObject(RedisKeyConstans.HOME_PAGE_KEY+deptId+"selectHighQualityUsersMONTH",map,getCacheInvalidTime());
				}
			}
			result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), CountResponseMsg.DATA_SELECT_SUCCESS.getMsg()), map);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), CountResponseMsg.DATA_SELECT_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 查询公会名称
	 * 
	 * @param code
	 * @throws Exception
	 */
	private String selectLabourUnionId(String code) throws Exception {
		Dept dept = this.deptService.selectByCode(code);
		if (dept != null && dept.getType() != null) {
			if (dept.getType() == 1) {
				return dept.getName();
			} else {
				return selectLabourUnionId(dept.getParentCode());
			}
		} else {
			return null;
		}
	}

	/**
	 * 查询公会名称
	 * 
	 * @param id
	 * @throws Exception
	 */
	private String selectLabourUnionNameById(String id) throws Exception {
		Dept dept = this.deptService.selectByPrimaryKey(id);
		if (dept != null) {
			if (dept.getType() == 1) {
				return dept.getName();
			} else {
				Dept parentDept = this.deptService.selectByCode(dept.getParentCode());
				if (parentDept != null) {
					return selectLabourUnionId(parentDept.getId());
				} else {
					return null;
				}
			}
		} else {
			return null;
		}
	}

	/**
	 * 查询组织架构接口
	 * 
	 * @param code
	 * @param list
	 * @throws Exception
	 */
	private void selectGroupId(String code, List<String> list) throws Exception {
		List<Dept> deptList = this.deptService.selectByParentCode(code);
		if (deptList != null) {
			for (Dept dept1 : deptList) {
				if (dept1.getType() == 6) {
					list.add(dept1.getId());
				}
				selectGroupId(dept1.getCode(), list);
			}
		}
	}

	/**
	 * 查询组织架构接口
	 * 
	 * @param code
	 * @param list
	 * @throws Exception
	 */
	private void selectSonId(String code, List<String> list) throws Exception {
		List<Dept> deptList = this.deptService.selectByParentCode(code);
		if (deptList != null) {
			for (Dept dept1 : deptList) {
				list.add(dept1.getId());
				selectSonId(dept1.getCode(), list);
			}
		}
	}

	/**
	 * 查询今日日期
	 * 
	 * @return
	 * @throws Exception
	 */
	private String getToday() throws Exception {
		SimpleDateFormat sim = new SimpleDateFormat("yyyy-MM-dd");
		return sim.format(new Date());
	}

	/**
	 * 查询本月第一天
	 * 
	 * @return
	 * @throws Exception
	 */
	private Date getMonthFirstDay() throws Exception {
		Calendar c = Calendar.getInstance();
		try {
			c.set(Calendar.DATE, 1);
			c.set(Calendar.HOUR_OF_DAY, 0);
			c.set(Calendar.MINUTE, 0);
			c.set(Calendar.SECOND, 0);
			c.set(Calendar.MILLISECOND, 0);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return c.getTime();
	}

	/**
	 * 获取失效时间
	 * @return
	 */
	private long getCacheInvalidTime(){
		LoginConfig loginConfig = ConfigManager.getInstance().parseObject(LoginConfig.class);
		long timeOut = 7200000;
		if(loginConfig!=null && loginConfig.getCacheInvalidTime()!=null){
			timeOut = loginConfig.getCacheInvalidTime()*60*1000;
		}
		return timeOut;
	}
}